#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <time.h>

#include "i3.h"
#include "i3_fun.h"
#include "i3_api.h"
#include "../i3_client/i3_client_api.h"
#include "../utils/utils.h"

/* read ID from a string */
void read_id(ID *id, char *hstr)
{
  int i;
  char h[3];
  int  dummy;

  for (i = 0; i < ID_LEN; i++) {
    /* covert from string into hexa number */
    h[0] = hstr[2*i];
    h[1] = hstr[2*i + 1];
    h[2] = 0;
    sscanf(h, "%x", &dummy);
    id->x[i] = dummy;
  }
}

void print_id(ID *id)
{
  uint i;
    
  for (i = 0; i < sizeof(ID); i++)
    printf("%02x", (int)(id->x[i])); 
  printf("\n");
}


/* set the key field of a given ID to a random value */
void set_random_key(Key *key)
{
  int   i;

  for(i=0; i < KEY_LEN; i++) {
    key->x[i] = (char) (n_rand(255));
  }
}

/* set the key field of a given ID to a random value */
void set_random_id(ID *id)
{
  int   i;

  for(i=0; i < ID_LEN; i++) {
    id->x[i] = (char) (n_rand(255));
  }
}


/* create stack */
ID *create_stack(int num, char **str_ids)
{
  int  i;
  ID  *s;
  ID  id;

  s = malloc(sizeof(ID)*num);
  for (i = 0; i < num; i++) {
    read_id(&id, str_ids[i]);
    memcpy(&s[i].x, &id.x, sizeof(ID));
  }
  return s;
}


void print_stack(ID *stack, int stack_len)
{
  int i;
  
  for (i = 0; i < stack_len; i++) {
    printf("[%d]:", i);
    print_id(&stack[i]);
  }
}


void init_id_fromstr(ID *id, char *name)
{
  uint i;

  for (i = 0; i < ID_LEN; i++)
    id->x[i] = name[i % strlen(name)];
}

void init_key_fromstr(Key *key, char *name)
{
  uint i;

  for (i = 0; i < KEY_LEN; i++)
    key->x[i] = name[i % strlen(name)];
}
